<?php

namespace app\service\live;

use \Exception;
use app\common\controller\Common;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Console\Console;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\SDK\Live\V20161101\Live;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Live\V20161101\Models\GetMessageTokenRequest;
use AlibabaCloud\SDK\Live\V20161101\Models\ForbidLiveStreamRequest;
use AlibabaCloud\SDK\Live\V20161101\Models\DescribeLiveStreamsBlockListRequest;
use AlibabaCloud\SDK\Live\V20161101\Models\DescribeLiveStreamsOnlineListRequest;


class LiveStream extends Common
{

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Live Client
     * @author tangfen
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/live
        $config->endpoint = "live.aliyuncs.com";
        return new Live($config);
    }


    /**
     * 使用STS鉴权方式初始化账号Client，推荐此方式。
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @param string $securityToken
     * @return Live Client
     * @author tangfen
     */
    public static function createClientWithSTS($accessKeyId, $accessKeySecret, $securityToken)
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret,
            // 必填，您的 Security Token
            "securityToken" => $securityToken,
            // 必填，表明使用 STS 方式
            "type" => "sts"
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/live
        $config->endpoint = "live.aliyuncs.com";
        return new Live($config);
    }


    /**
     * 禁止某条流的推送，可以预设某个时刻将流恢复
     * $appName 推流所属应用名称
     * $streamName 推流名称
     * @author tangfen
     */
    public function ForbidLiveStream($appName, $streamName)
    {

        $client = self::createClient(config('aly_config.accessKeyId'), config('aly_config.accessKeySecret'));

        $forbidLiveStreamRequest = new ForbidLiveStreamRequest([
            "domainName" => "推流域名",//推流域名
            "appName" => $appName,//推流所属应用名称
            "streamName" => $streamName,//推流名称
            "liveStreamType" => "publisher",//主播端
            "oneshot" => "no",
            "resumeTime" => ""//恢复流的时间 格式为：yyyy-MM-ddTHH:mm:ssZ（UTC 时间）    不传值指定时间禁止直播流则为永久生效
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->forbidLiveStreamWithOptions($forbidLiveStreamRequest, $runtime);
            $data = json_decode(Utils::toJSONString($res), true);
            if ($data['statusCode'] == 200) {
                return $data['body'];
            }
            return $data;

        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 错误 message
//            var_dump($error->message);
            // 错误 message
            // 诊断地址
            return $error->data;
            Utils::assertAsString($error->message);
        }


    }

    /**
     * 查询指定域名或者指定域名下某个应用的所有在线流信息
     * $appName 主播流域名
     * $streamName 播流所属应用名称
     * @author tangfen
     */
    public function DescribeLiveStreamsOnlineList($appName, $streamName)
    {

        $client = self::createClient(config('aly_config.accessKeyId'), config('aly_config.accessKeySecret'));
        $describeLiveStreamsOnlineListRequest = new DescribeLiveStreamsOnlineListRequest([
            "domainName" => "主播流域名",//主播流域名
            "appName" => $appName,
            "streamName" => $streamName,
            "onlyStream" => 'no',//是否只返回指定字段 yes：结果只返回 DomainName，AppName，StreamName，PublishTime 字段。 no（默认值）：结果返回全部字段。
            "streamType" => "all",
            "queryType" => "fuzzy",
            "pageSize" => 15,
            "pageNum" => 1
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->describeLiveStreamsOnlineListWithOptions($describeLiveStreamsOnlineListRequest, $runtime);
            $data = json_decode(Utils::toJSONString($res), true);
            if ($data['statusCode'] == 200) {
                return $data['body'];
            }
            return $data;

        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 错误 message
//            var_dump($error->message);
            // 错误 message
            // 诊断地址
            return $error->data;
            // 诊断地址
            Utils::assertAsString($error->message);
        }
    }


    /**
     * 获取域名下直播流播放的黑名单
     * $domainName  主播流域名
     * @author tangfen
     */
    public function DescribeLiveStreamsBlockList($domainName = '')
    {

        $client = self::createClient(config('aly_config.accessKeyId'), config('aly_config.accessKeySecret'));

        $describeLiveStreamsBlockListRequest = new DescribeLiveStreamsBlockListRequest([
            "domainName" => $domainName,//主播流域名
            "pageNum" => 1
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->describeLiveStreamsBlockListWithOptions($describeLiveStreamsBlockListRequest, $runtime);

            $data = json_decode(Utils::toJSONString($res), true);
            if ($data['statusCode'] == 200) {
                return $data['body'];
            }
            return $data;

        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 错误 message
            // 诊断地址
            return $error->data;
            Utils::assertAsString($error->message);
        }
    }


    /**
     *  获取长连接建连Token   获取互动消息服务端鉴权token
     * $deviceId  终端设备ID 最大长度64位字符 前端给
     * $userId  唯一最大32字符  唯一
     * @author tangfen
     */
    public function GetMessageToken($deviceId, $userId)
    {

        $client = self::createClient(config('aly_config.accessKeyId'), config('aly_config.accessKeySecret'));

        $getMessageTokenRequest = new GetMessageTokenRequest([
            "appId" => "tianyue",//唯一就行
            "deviceId" => $deviceId,//终端设备ID 最大长度64位字符
            "deviceType" => "web",//ios Android
            "userId" => $userId//唯一最大32字符
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->getMessageTokenWithOptions($getMessageTokenRequest, $runtime);
            $data = json_decode(Utils::toJSONString($res), true);
            if ($data['statusCode'] == 200) {
                return $data['body'];
            }
            return $data;
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 错误 message
//            var_dump($error->message);

            $data = json_decode(Utils::toJSONString($error), true);
            return $data;
            // 诊断地址
//            var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }

    }


}
